package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.adapter.ScoreManageAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.ScoreManageResponse;
import com.ycsj.goldmedalnewconcept.bean.ScoreManageResponse.TestTheme;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.R;

//成绩管理 教师端
public class ScoreManageActivity extends Activity implements OnRefreshListener,
		OnClickListener {
	private ListView lv_friends;
	private ScoreManageAdapter mAdapter;
	private ImageView iv_back;
	private TextView tv_testthme;
	private PullToRefreshLayout refreshLayout;
	private List<TestTheme> list;
	private List<TestTheme> list2;
	private String role; 
	private String account;
	private String rowid;
	private int page = 0;
	private TextView loadTextView;
	private TextView tv_empty;
	private View footerView;
	private View loading;
	private boolean isLoading = false;
	private RotateAnimation loadingAnimation;
	private String userclass;
	private String num;;
	private Intent intent;
	private String team;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_scoremanage);

		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");

		intent = getIntent();
		userclass = intent.getStringExtra("class_id");
		num = intent.getStringExtra("num");
		team = intent.getStringExtra("team");
		
		list = new ArrayList<TestTheme>();
		list2 = new ArrayList<TestTheme>();

		loadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
				this, R.anim.rotating);
		// 添加匀速转动动画
		LinearInterpolator lir = new LinearInterpolator();
		loadingAnimation.setInterpolator(lir);
		
		initView();
		setOnListener();
		initData();
	}


	private void initView() {
		tv_testthme = (TextView) findViewById(R.id.tv_newscoremanage);
		
		lv_friends = (ListView) findViewById(R.id.lv_scoremanage);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		refreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		
		footerView = this.getLayoutInflater().inflate(
				R.layout.load_more_jpstar, null);
		loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);
		tv_empty = (TextView)findViewById(R.id.tv_empty);
		lv_friends.addFooterView(footerView, null, false);
		footerView.setOnClickListener(this);
		
	}

	private void setOnListener() {
		refreshLayout.setOnRefreshListener(this);

		iv_back.setOnClickListener(this);
		tv_testthme.setOnClickListener(this);
	}	

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "36");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("userclass", userclass);
		builder.add("page", page + "");
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=36&c=13006314760&role=2&userclass=2722&page=0
//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=33&c=13006314760&role=2&userclass=2722&tag=123&status=0
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				
				
				ScoreManageResponse fromJson = gson.fromJson(json,
						ScoreManageResponse.class);

				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							|| "0".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								if(page == 0){
									tv_empty
									 .setVisibility(tv_empty.VISIBLE);
								}
								
								
								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								loadTextView.setText("已经是最后一条了");
								loadTextView.setClickable(false);
								isLoading = true;
								page = 0;
							}
						});
					} else if ("1".equals(fromJson.state)) {
						list2 = fromJson.list;
						if(page==0){
							list = list2;
						}else{
							list.addAll(list2);
						}
						
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								tv_empty
								 .setVisibility(tv_empty.GONE);
								refreshLayout
											.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
								mAdapter = new ScoreManageAdapter(
										ScoreManageActivity.this, list); 
								if(page==0){
									
									lv_friends.setAdapter(mAdapter);
									
								}else{
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											mAdapter.notifyDataSetChanged();
										}
									});
								}
								
								lv_friends.setOnItemClickListener(new OnItemClickListener() {

									

									

									@Override
									public void onItemClick(
											AdapterView<?> parent, View view,
											int position, long id) {
										//测试主题
										Intent intent = new Intent(ScoreManageActivity.this,ScoreThemeActivity.class);
										intent.putExtra("rowid", list.get(position).row_id+"");
										intent.putExtra("userclass", userclass);
										intent.putExtra("tag", list.get(position).tag);
										intent.putExtra("num", num);
										intent.putExtra("team", team);
										
										startActivity(intent);
										
									}
								});
								
									lv_friends.setOnItemLongClickListener(new OnItemLongClickListener() {

												@Override
												public boolean onItemLongClick(
														AdapterView<?> parent,
														View view,
														int position, long id) {
													rowid = list.get(position).row_id+"";
													Log.e("test", rowid);
													deldialog(rowid);//删除条目的弹窗
													return true;
												}

												private BaseAnimatorSet bas_in;
												private BaseAnimatorSet bas_out;

												public void setBasIn(
														BaseAnimatorSet bas_in) {
													this.bas_in = bas_in;
												}

												public void setBasOut(
														BaseAnimatorSet bas_out) {
													this.bas_out = bas_out;
												}

												private void deldialog(final String rowid) {
													
													final NormalDialog dialog = new NormalDialog(
															ScoreManageActivity.this);
													dialog.content("确定删除此测试主题？")
															.btnText("取消", "确认")//
															.style(NormalDialog.STYLE_TWO)//
															.titleTextSize(23)//
															.showAnim(bas_in)//
															.dismissAnim(
																	bas_out)//
															.show();
													dialog.setCanceledOnTouchOutside(false);
													dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

														@Override
														public void onBtnLeftClick() {
															dialog.dismiss();
														}
													});
													dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

														@Override
														public void onBtnRightClick() {
															//删除条目
															dialog.dismiss();
															
															OkHttpClient mOkHttpClient = new OkHttpClient();
															FormEncodingBuilder builder = new FormEncodingBuilder();
															builder.add("type", "35");
															builder.add("rowid",rowid);
															builder.add("c", account);
															builder.add("role", role);
															builder.add("status", "0");
															Request request = new Request.Builder()
																	.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
																	.build();
															mOkHttpClient.newCall(request).enqueue(new Callback() {

																@Override
																public void onFailure(Request arg0, IOException arg1) {
																	runOnUiThread(new Runnable() {
																		@Override
																		public void run() {
																			Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
																					.show();
																		}
																	});
																}

																@Override
																public void onResponse(Response arg0) throws IOException {
																	// 解析Json数据，保存登录状态及身份信息

																	Gson gson = new Gson();
																	String json = arg0.body().string();
																	Log.e("test", json);
																	AttResponse fromJson = gson.fromJson(json,
																			AttResponse.class);

																	if (fromJson != null) {
																		if ("-1".equals(fromJson.state)
																				|| "0".equals(fromJson.state)) {
																			runOnUiThread(new Runnable() {
																				@Override
																				public void run() {
																					Toast.makeText(getBaseContext(), "删除失败，请检查网络连接是否正常", 0)
																					.show();
																				}
																			});
																		} else if ("1".equals(fromJson.state)) {
																			
																			runOnUiThread(new Runnable() {
																				@Override
																				public void run() {
																					onRefresh();
																					Toast.makeText(getBaseContext(), "删除成功！", 0)
																					.show();
																					
																				}
																			});
																		}
																	}
																}
															});
															
															
														}
													});

												}
											});
								
								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								if(list2.size()<5){
									loadTextView.setText("已经是最后一条了");
									loadTextView.setClickable(false);
									isLoading = true;
									page = 0;
								}else{
									loadTextView.setText("加载更多");
									isLoading = false;
								}
							}
						});
					}
				}
			}
		});
	}
  
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_newscoremanage://新建测试主题
		    final EditText et = new EditText(this);  
		    et.setBackgroundResource(R.color.white);
            
		    new AlertDialog.Builder(this).setTitle("添加测试主题")  
		    .setIcon(android.R.drawable.ic_dialog_info)  
		    .setView(et)  
		    .setPositiveButton("确定", new DialogInterface.OnClickListener() {  
		        public void onClick(DialogInterface dialog, int which) {  
		        String input = et.getText().toString();  
		        if ("".equals(input)) {  
		            Toast.makeText(getApplicationContext(), "主题内容不能为空！" + input, Toast.LENGTH_LONG).show();  
		        }  
		        else {  
		        	OkHttpClient mOkHttpClient = new OkHttpClient();
		    		FormEncodingBuilder builder = new FormEncodingBuilder();
		    		builder.add("type", "33");
		    		builder.add("c", account);
		    		builder.add("role", role);
		    		builder.add("userclass", userclass);
		    		builder.add("tag", input);
		    		builder.add("status", "0");
		    		Request request = new Request.Builder()
		    				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
		    				.build();
		    		mOkHttpClient.newCall(request).enqueue(new Callback() {
		    //http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=33&c=13006314760&role=2&userclass=2722&tag=123&status=0
		    			@Override
		    			public void onFailure(Request arg0, IOException arg1) {
		    				runOnUiThread(new Runnable() {
		    					@Override
		    					public void run() {
		    						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
		    								.show();
		    					}
		    				});
		    			}

		    			@Override
		    			public void onResponse(Response arg0) throws IOException {
		    				// 解析Json数据，保存登录状态及身份信息

		    				Gson gson = new Gson();
		    				String json = arg0.body().string();
		    				Log.e("test", json);
		    				
		    				AttResponse fromJson = gson.fromJson(json,
		    						AttResponse.class);

		    				if (fromJson != null) {
		    					if ("-1".equals(fromJson.state)
		    							|| "0".equals(fromJson.state)) {
		    						runOnUiThread(new Runnable() {
				    					@Override
				    					public void run() {
				    						Toast.makeText(getBaseContext(), "服务器开小差了，请重新添加", 0)
				    								.show();
				    					}
				    				});
		    					} else if ("1".equals(fromJson.state)) {
		    						
		    						runOnUiThread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Toast.makeText(getBaseContext(), "测试主题创建成功！", 0)
		    								.show();
											onRefresh();
										}
		    						});
		    					}
		    				}
		    			}
		    		});
		            }  
		        }
		        })  
		    .setNegativeButton("取消", null)  
		    .show();  
			
			break;
		case R.id.loadmore_layout:
			if (!isLoading) {
				loading.setVisibility(View.VISIBLE);
				loading.startAnimation(loadingAnimation);
				loadTextView.setText("正在加载...");
				isLoading = true;
				page++;
				initData();
			}
			break;
		}
	}
@Override
protected void onRestart() {
	// TODO Auto-generated method stub
	super.onRestart();
	onRefresh();
}
	@Override
	public void onRefresh() {
		// 下拉刷新操作
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				page = 0;
				initData();
				loadTextView.setText("加载更多");
				loading.setVisibility(View.GONE);
				isLoading = false;
				
			}
		}, 500);
	}

}
